package com.browsesoft.htmlcomponent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.browsesoft.dbtools.DBTools;

public class HTMLDocPageModel implements HTMLBasicModel {
	/**
	 * Model所对应的component
	 */
	protected HTMLBasicComponent component = null;

	String[][] datas = null;

	String tableName = null;

	/**
	 * 初始化model
	 */

	public void init(HttpServletRequest request) throws Exception {
	}

	/**
	 * 处理用户请求
	 * 
	 * @param request
	 *            客户端请求
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		tableName = component.element.getAttribute("tablename");
		String id = request.getParameter("id");
		datas = DBTools.executeQueryWithTableHead("select * from " + tableName
				+ " where id=" + id);
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
		this.component = component;
	}

	/**
	 * 由Component决定需要Model处理的元素内容，在Component的updateElement()方法中调用
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 获取文档的给定字段的内容
	 */
	public String getFieldContent(String field) throws Exception {
		String fieldContent = "";
		int index = DBTools.indexOf(datas[0], field);
		if (index != -1) {
			if (datas.length == 2) {
				fieldContent = datas[1][index];
			}
		}
		return fieldContent;
	}

	/**
	 * 设置文本区域元素的内容
	 */
	public void setContext(Element e, Document doc) throws Exception {
		String temp = "";
		String fieldContent = this.getFieldContent(e.getAttribute("fieldtype"));
		String unite = e.getAttribute("unite");
		// 是否需要合并
		if (unite != null && !unite.equals("")) {
			String uniteStr = fieldContent;
			String unitetemp = "";
			int uniteNumber = Integer.parseInt(unite);
			// 合并字符串
			for (int i = 0; i < uniteNumber; i++) {
				unitetemp = this.getFieldContent(e.getAttribute("fieldtype")
						+ "_" + i);
				if (unitetemp != null) {
					uniteStr += unitetemp;
				}
			}
			fieldContent = uniteStr;
		}
		java.util.StringTokenizer stk = new java.util.StringTokenizer(
				fieldContent, "\n");
		if (stk.countTokens() == 1) {
			e.appendChild(doc.createTextNode(fieldContent));
		} else {
			while (stk.hasMoreTokens()) {
				temp = stk.nextToken();
				e.appendChild(doc.createTextNode(temp));
				e.appendChild(doc.createElement("br"));
			}
		}
	}
}